import React, { useEffect, useMemo, useState } from 'react'
import { ServerInfo } from '../../apis'
import ReactEcharts from './ReactEcharts'
import dayjs from 'dayjs'

interface Props {
    info: ServerInfo
}
const System = (props: Props) => {
    const [infos, setInfos] = useState<ServerInfo[]>([])
    useEffect(() => {
        if (props.info) {
            const result = [...infos, props.info]
            if (result.length > 60) {
                result.shift()
            }
            setInfos(result)
        }
    }, [props.info])

    const option = useMemo(function () {
        const times: string[] = []
        const data_mem: number[] = []
        const data_cpu: number[] = []
        infos.map(i => {
            times.push(dayjs(i.now).format('HH:mm:ss'))
            data_mem.push(i.memPercent)
            data_cpu.push(i.cpuPercent)
        })

        const option: echarts.EChartsOption = {
            title: [
                { text: '内存使用率' },
                { text: 'CPU使用率', top: '50%', },
            ],
            visualMap: [
                { show: false, type: 'continuous', seriesIndex: 0, min: 0, max: 100 },
                { show: false, type: 'continuous', seriesIndex: 1, min: 0, max: 100 },
            ],
            tooltip: { trigger: 'axis' },
            xAxis: [
                { data: times },
                { data: times, gridIndex: 1 },
            ],
            yAxis: [
                { max: 100, axisLabel: { formatter: '{value}%' } },
                { max: 100, axisLabel: { formatter: '{value}%' }, gridIndex: 1 },
            ],
            grid: [
                { top: '5%', bottom: '60%' },
                { top: '60%', bottom: '5%' },
            ],
            series: [
                { type: 'line', smooth: true, showSymbol: false, data: data_mem },
                { type: 'line', smooth: true, showSymbol: false, data: data_cpu, xAxisIndex: 1, yAxisIndex: 1 },
            ],
        }
        return option
    }, [infos])

    return (
        <ReactEcharts option={option} height={document.documentElement.clientHeight - 210}/>
    )
}

export default System